package com.binguo.wxapi.service;

import com.alibaba.fastjson.JSON;


import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import com.binguo.common.util.UrlUtils;
import com.binguo.helper.WxAppHelper;
import com.binguo.model.mapper.*;

import com.binguo.model.model.*;

import com.binguo.model.wxapi.vo.AiyouweiGetCellVO;
import com.binguo.model.wxapi.vo.SideBoardVO;


import com.binguo.wxapi.form.PhoneMealsForm;
import com.binguo.wxapi.form.aiyouwei.SaveOrderForm;

import com.binguo.wxapi.transfer.OrderNoBuilder;
import com.binguo.wxapi.util.BarcodeUtil;

import org.aspectj.apache.bcel.generic.FieldOrMethod;
import tk.mybatis.mapper.entity.Condition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;



@Service
public class AiyouweiService {


    @Resource
    private BinguoOrderMapper binguoOrderMapper;

    @Resource
    private SideBoardCellDetailMapper sideBoardCellDetailMapper;

    @Resource
    private SideBoardMapper sideBoardMapper;

    @Resource
    private SideBoardCellsMapper sideBoardCellsMapper;
    @Autowired
    private OrderNoBuilder orderNoBuilder;

    @Resource
    private WXCustomerService wxCustomerService;

    @Resource
    private ShopConfigExtendMapper shopConfigExtendMapper;

    @Resource
    private BaiduSdkSerialNumMapper baiduSdkSerialNumMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private BranchMapper branchMapper;


    private String token = "";
    private static final Logger logger = LoggerFactory.getLogger(AiyouweiService.class);
    /**
     * 商户或客户订单详情页存取餐二维码生成
     *
     * @return base64 二维码图片
     */
    public String getQrCode(SaveOrderForm saveOrderForm) {
        //1.根据订单号查找出订单
        BinguoOrder binguoOrder = binguoOrderMapper.findOrderByOrderNo(saveOrderForm.getOrderId());
        //2.根据订单号查找出该订单餐盘所在格
        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(binguoOrder.getOrderno());
        criteria.andShopIdEqualTo(binguoOrder.getShopid());
        criteria.andBranchIdEqualTo(binguoOrder.getBranchid());
        List<SideBoardCellDetail> list = sideBoardCellDetailMapper.selectByExample(example);
        //sf.setCellNo(list.get(0).getCell());
        saveOrderForm.setMealCode(list.get(0).getMealCode());
        saveOrderForm.setBranchId(binguoOrder.getBranchid());
        saveOrderForm.setShopId(binguoOrder.getShopid());
        //实体类转String后调用二维码生成接口
        String json = JSON.toJSONString(saveOrderForm);
        return BarcodeUtil.generateFile7(json);
    }

    /**
     * 商户绑定自提柜
     *
     * @param sideBoard 自提柜信息
     * @return
     */
    public Integer initSideBoard(SideBoard sideBoard) {

        return sideBoardMapper.insertSelective(sideBoard);
    }

    public Integer initSideBoardCells(List<SideBoardCells> list){

        return sideBoardCellsMapper.insertByList(list);
    }

    /**
     * 查询订单状态
     */
    public List<SideBoardCells> selectSideBoardCells(String orderId) {
        SideBoardCellsExample sideBoardCellsExample = new SideBoardCellsExample();
        SideBoardCellsExample.Criteria exam = sideBoardCellsExample.createCriteria();
        exam.andOrderIdEqualTo(orderId);
        return sideBoardCellsMapper.selectByExample(sideBoardCellsExample);
    }

    /**
     * 存取餐完成后更新SideBoardCells表
     *
     * @param sideBoardCells
     * @return
     */
    public Integer updateSideBoardCells(SideBoardCells sideBoardCells) {

        return sideBoardCellsMapper.updateByPrimaryKeySelective(sideBoardCells);
    }

    /**
     * 商户存餐完成后新增一条side_board_cell_detail记录
     *
     * @param sideBoardCellDetail
     * @return
     */
    public Integer insertSideBoardCellDetail(SideBoardCellDetail sideBoardCellDetail) {
        return sideBoardCellDetailMapper.insertSelective(sideBoardCellDetail);
    }

    /**
     * 查询一个未使用的餐柜格子
     *
     * @param branchId
     * @param shopId
     * @return
     */
    public AiyouweiGetCellVO selectAllNotUseCell(Integer branchId, Integer shopId) {

        return sideBoardMapper.selectAllNotUseCell(branchId, shopId);

    }

    /**
     * 查询一个未使用的餐柜格子
     *
     * @param branchId
     * @param shopId
     * @return
     */
    public AiyouweiGetCellVO selectCell(Integer branchId, Integer shopId,Integer cell) {

        return sideBoardMapper.selectCell(branchId, shopId,cell);

    }


    /**
     * 查询订单状态
     *
     * @param s
     * @return
     */
    public List<SideBoardCellDetail> selectSideBoardCellDetail(SideBoardCellDetailExample s) {

        return sideBoardCellDetailMapper.selectByExample(s);
    }

    /**
     * 取餐完成后更新side_board_cell_detail表
     *
     * @param sideBoardCellDetail
     * @return
     */
    public Integer updateSideBoardCellDetail(SideBoardCellDetail sideBoardCellDetail) {

        return sideBoardCellDetailMapper.updateByPrimaryKey(sideBoardCellDetail);
    }

    /**
     * 查询当前分店所有的柜格状态

     * @return
     */
    public List<SideBoardCells> selectAllSideBoardCell(Integer id) {

        return sideBoardCellsMapper.selectAllSideBoardCell(id);
    }

    /**
     * 生成四位不重复取餐码1
     * @return
     */
    /*public String getNewMealCode(Integer sideBoardId){
        SideBoardCellsExample example = new SideBoardCellsExample();
        SideBoardCellsExample.Criteria criteria = example.createCriteria();
        criteria.andSideBoardIdEqualTo(sideBoardId);
        criteria.andMealCodeIsNotNull();
        List<SideBoardCells> sideBoardCells = sideBoardCellsMapper.selectByExample(example);
        return getNewArray(sideBoardCells);

    }*/

    /**
     * 生成四位不重复取餐码2
     * @return
     */
    public String getMealCode(String orderId){
        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andMealCodeIsNotNull();
        List<SideBoardCellDetail> sideBoardCells = sideBoardCellDetailMapper.selectByExample(example);
        return getNewArray(sideBoardCells);

    }

    /**
     * 生成随机不重复取餐码方案
     * @param array
     * @return
     */
    public String getNewArray(List<SideBoardCellDetail> array){
        String k = "";
        while(true){
            String s = String.valueOf((int)((Math.random()*9+1)*1000));
            for (int i = 0; i < array.size();i++ ){
                if(s.equals(array.get(i).getMealCode())){
                    k = array.get(i).getMealCode();
                }
            }
            if(!s.equals(k)){
                return s;
            }else{
                continue;
            }
        }
    }

    /**
     * 获取取餐码
     * @param orderId
     * @return 取餐码
     */
    public String getSideBoardCellDetailByOrderId(String orderId){
        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<SideBoardCellDetail> sideBoardCells = sideBoardCellDetailMapper.selectByExample(example);

        return sideBoardCells.get(0).getMealCode();
    }

    public String isOneOrderToSomeCell(String orderId){
        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<SideBoardCellDetail> sideBoardCells = sideBoardCellDetailMapper.selectByExample(example);
        if(sideBoardCells.size()>0){
            return sideBoardCells.get(0).getMealCode();
        }else{
            return "";
        }
    }


    public SideBoardCellDetail  getSideBoardCellsDetail(String orderId){
        return  sideBoardCellDetailMapper.selectByOrderIdAndCell(orderId);
    }

    public List<SideBoardCellDetail>  getSideBoardCellsExample(String orderId){
        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        return  sideBoardCellDetailMapper.selectByExample(example);
    }

    public List<SideBoardCells> getSideBoardCells(String orderId){
        SideBoardCellsExample example = new SideBoardCellsExample();
        SideBoardCellsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        return sideBoardCellsMapper.selectByExample(example);
    }


    public SideBoard getSideBoardByMealCode(String code){

        return sideBoardMapper.selectByMealCode(code);
    }


    public List<SideBoardCells> getSideBoarSidels(String code){
        SideBoardCellsExample example = new SideBoardCellsExample();
        SideBoardCellsExample.Criteria criteria = example.createCriteria();
        criteria.andMealCodeEqualTo(code);
        return sideBoardCellsMapper.selectByExample(example);
    }

    public Integer insertDetail(SideBoardCellDetail sideBoardCellDetail){
        return  sideBoardCellDetailMapper.insertSelective(sideBoardCellDetail);
    }


    public SideBoard selectById(Integer id){

        return sideBoardMapper.selectByPrimaryKey(id);
    }

    public  SideBoardVO phoneMeals(PhoneMealsForm form){
        AiyouweiGetCellVO aiyouweiGetCellVO =
                selectAllNotUseCell(form.getBranchId(),form.getShopId());
        if(null == aiyouweiGetCellVO){
            return null;
        }
        Long totalPrice = 0l;
        Integer meshOrderSerialInt = 0;
        String orderNo = orderNoBuilder.createPlatformOrderNo();
        SideBoardVO sideBoardVO =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());
        SideBoardVO sideBoardVO1 = sideBoardMapper.selectByShopIdAndBranchId(form.getBranchId(),form.getShopId(),form.getCashierDeskId());
        totalPrice += sideBoardVO.getPrice();
        if(form.getIsWarm() == true){
            totalPrice += sideBoardVO.getWarm();
        }
        BinguoOrder binguoOrder = BinguoOrder.builder()
                .orderno(orderNo)
                .serial(meshOrderSerialInt.toString())
                .serialnumber(orderNo)
                .created(new Date())
                .customerphone(form.getPhone())
                .totalfee(totalPrice)
                .realfee(totalPrice)
                .cashierdeskid(form.getCashierDeskId())
                .ordertype(4)
                .paystatus(new Byte("0"))
                .refundfee(0L)
                .shopid(form.getShopId())
                .totalquantity(1)
                .branchid(form.getBranchId())
                .isMeals(1)
                .isWarm(form.getIsWarm() ==true ? 1:0)
                .build();
        List<OrderItem> items = new ArrayList<>();
        items.add(OrderItem.builder()
                .orderno(orderNo)
                .productid(-5)
                .productname("自定义菜品")
                .price(0L)
                .realprice(0L)
                .quantity(1)
                .created(new Date())
                .updated(new Date()).build());
        MeshOrder meshOrder = new MeshOrder();

        BeanUtils.copyProperties(binguoOrder, meshOrder);
        meshOrder.setReadStatus(0);


        List<MeshOrderItem> meshOrderItemList = new ArrayList<>();
        for (OrderItem orderItem : items) {
            MeshOrderItem meshOrderItem = new MeshOrderItem();
            BeanUtils.copyProperties(orderItem, meshOrderItem);
            meshOrderItemList.add(meshOrderItem);
        }
        //下单生成取餐码
        SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
        sideBoardCellDetail.setId(0);
        sideBoardCellDetail.setOrderStatus(0);
        sideBoardCellDetail.setOrderId(binguoOrder.getOrderno());
        sideBoardCellDetail.setBranchId(form.getBranchId());
        sideBoardCellDetail.setShopId(form.getShopId());
        String code = getMealCode(binguoOrder.getOrderno());

        sideBoardCellDetail.setMealCode(code);
        sideBoardVO1.setMealCode(code);
        System.out.println("sideBoardVO1:"+sideBoardVO1);
        int i = insertSideBoardCellDetail(sideBoardCellDetail);
        System.err.println("插入返回结果:"+i);
        try{
            wxCustomerService.saveOrder(binguoOrder, items, meshOrder, meshOrderItemList);
            return sideBoardVO1;
        }catch(Exception e){
            return null;
        }
    }

    /**
     * 取餐柜获取百度人脸识别sdk序列号
     * @return String
     */
    public String getBaiduSDKSerial(String deviceId){
        logger.info("根据设备号:"+deviceId+"查找序列号");
        return baiduSdkSerialNumMapper.selectSerialByDeviceId(deviceId);
    }

    /**
     * 取餐柜获取最小的一条未激活的百度人脸识别sdk序列号
     * @return String
     */
    public BaiduSdkSerialNum getNoUseBaiduSDKSerial(){
        logger.info("获取一条未使用的序列号");
        return baiduSdkSerialNumMapper.selectNoUseSerialByDeviceId();
    }

    /**
     * 取餐柜绑定序列号
     * @return String
     */
    public Integer serialBindSideBoard(BaiduSdkSerialNum baiduSdkSerialNum){
        logger.info("取餐柜准备绑定序列号,入参:"+baiduSdkSerialNum);
        return baiduSdkSerialNumMapper.updateByPrimaryKey(baiduSdkSerialNum);
    }

    public SideBoardVO phoneMealApi(PhoneMealsForm form,Customer customer){
        logger.info(form.toString());
        logger.info(customer.toString());
        AiyouweiGetCellVO aiyouweiGetCellVO =
                selectAllNotUseCell(form.getBranchId(),form.getShopId());
        if(null == aiyouweiGetCellVO){
            return null;
        }
        if(null == form.getDeviceId()){
            form.setDeviceId(form.getCashierDeskId());
        }
        Long totalPrice = 0l;
        Integer meshOrderSerialInt = 0;
        String orderNo = orderNoBuilder.createPlatformOrderNo();
        SideBoardVO sideBoardVO =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());
        SideBoardVO sideBoardVO1 = sideBoardMapper.selectByShopIdAndBranchId(form.getBranchId(),form.getShopId(),form.getDeviceId());
        logger.info(sideBoardVO1.toString());
        totalPrice += sideBoardVO.getPrice();
        if(form.getIsWarm() == true){
            totalPrice += sideBoardVO.getWarm();
        }
        BinguoOrder binguoOrder = BinguoOrder.builder()
                .orderno(orderNo)
                .serial(meshOrderSerialInt.toString())
                .serialnumber(orderNo)
                .created(new Date())
                .customerphone(form.getPhone())
                .totalfee(totalPrice)
                .realfee(totalPrice)
                .cashierdeskid(form.getCashierDeskId())
                .ordertype(4).customerid(customer.getId())
                .paystatus(new Byte("1"))
                .refundfee(0L)
                .shopid(form.getShopId())
                .totalquantity(1)
                .branchid(form.getBranchId())
                .isMeals(1)
                .isWarm(form.getIsWarm() == true ? 1:0)
                .customername(form.getName())
                .build();
        List<OrderItem> items = new ArrayList<>();
        items.add(OrderItem.builder()
                .orderno(orderNo)
                .productid(-5)
                .productname("自定义菜品")
                .price(0L)
                .realprice(0L)
                .quantity(1)
                .created(new Date())
                .updated(new Date()).build());
        MeshOrder meshOrder = new MeshOrder();

        BeanUtils.copyProperties(binguoOrder, meshOrder);
        meshOrder.setReadStatus(0);


        List<MeshOrderItem> meshOrderItemList = new ArrayList<>();
        for (OrderItem orderItem : items) {
            MeshOrderItem meshOrderItem = new MeshOrderItem();
            BeanUtils.copyProperties(orderItem, meshOrderItem);
            meshOrderItemList.add(meshOrderItem);
        }
        //下单生成取餐码
        SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
        sideBoardCellDetail.setId(0);
        sideBoardCellDetail.setOrderStatus(0);
        sideBoardCellDetail.setOrderId(binguoOrder.getOrderno());
        sideBoardCellDetail.setBranchId(form.getBranchId());
        sideBoardCellDetail.setShopId(form.getShopId());
        String code = getMealCode(binguoOrder.getOrderno());
        logger.info("取餐码:"+code);

        sideBoardCellDetail.setMealCode(code);
        sideBoardVO1.setMealCode(code);
        System.out.println("sideBoardVO1:"+sideBoardVO1);
        int i = insertSideBoardCellDetail(sideBoardCellDetail);
        System.err.println("插入返回结果:"+i);
        try{
            wxCustomerService.saveOrder(binguoOrder, items, meshOrder, meshOrderItemList);
            return sideBoardVO1;
        }catch(Exception e){
            return null;
        }

    }
    public List<SideBoardCellDetail> selectSbDetails(SaveOrderForm saveOrderForm){
        //效验柜子号
        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
        criteria.andOrderStatusBetween(0,1);
        criteria.andMealCodeEqualTo(saveOrderForm.getMealCode());
        criteria.andShopIdEqualTo(saveOrderForm.getShopId());
        criteria.andBranchIdEqualTo(saveOrderForm.getBranchId());
        return sideBoardCellDetailMapper.selectByExample(example);
    }
    public Integer selectShopBranchList(String appId){
        Condition condition = new Condition(Shop.class);
        condition.or().andEqualTo("appId",appId);
        Shop shop = shopMapper.selectByCondition(condition).get(0);
        if(null != shop){
            condition = new Condition(Branch.class);
            condition.or().andEqualTo("shopId",shop.getId());
            List<Branch> branches =  branchMapper.selectByCondition(condition);
            if(null == branches){
                return -300;
            }else if(branches.size() == 1){
                return branches.get(0).getBranchId();
            }else{
                return -100;
            }
        }else{
            return -200;
        }
    }

    public String generateMiniProgramCode(String sideBoardId){
        if(StringUtils.isBlank(token)){
            token = UrlUtils.getAccessToken(WxAppHelper.APPID,WxAppHelper.SECRET).get("access_token").toString();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("page","pages/me");
        jsonObject.put("scene","id="+sideBoardId);
        return UrlUtils.sendPostForBuffer(jsonObject,"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token);
    }

    public List<SideBoard> getSideBoardByCashierDeskId(Integer cashierDeskId){
        return sideBoardMapper.selectListByCashierId(cashierDeskId);
    }

    public  SideBoardVO phoneMealZSD(PhoneMealsForm form){
        AiyouweiGetCellVO aiyouweiGetCellVO =
                selectAllNotUseCell(form.getBranchId(),form.getShopId());
        if(null == aiyouweiGetCellVO){
            return null;
        }
        Long totalPrice = 0L;
        Integer meshOrderSerialInt = 0;
        String orderNo = orderNoBuilder.createPlatformOrderNo();
        SideBoardVO sideBoardVO =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());
        SideBoardVO sideBoardVO1 = sideBoardMapper.selectByShopIdAndBranchId(form.getBranchId(),form.getShopId(),form.getCashierDeskId());
        totalPrice += sideBoardVO.getPrice();
        if(form.getIsWarm() == true){
            totalPrice += sideBoardVO.getWarm();
        }
        BinguoOrder binguoOrder = BinguoOrder.builder()
                .orderno(orderNo)
                .serial(meshOrderSerialInt.toString())
                .serialnumber(orderNo)
                .created(new Date())
                .customerphone(form.getPhone())
                .totalfee(totalPrice)
                .realfee(totalPrice)
                .cashierdeskid(form.getCashierDeskId())
                .ordertype(4)
                .paystatus(new Byte("0"))
                .refundfee(0L)
                .shopid(form.getShopId())
                .totalquantity(1)
                .branchid(form.getBranchId())
                .isMeals(1)
                .isWarm(form.getIsWarm() ==true ? 1:0)
                .build();
        List<OrderItem> items = new ArrayList<>();
        items.add(OrderItem.builder()
                .orderno(orderNo)
                .productid(-5)
                .productname("自定义菜品")
                .price(0L)
                .realprice(0L)
                .quantity(1)
                .created(new Date())
                .updated(new Date()).build());
        MeshOrder meshOrder = new MeshOrder();

        BeanUtils.copyProperties(binguoOrder, meshOrder);
        meshOrder.setReadStatus(0);


        List<MeshOrderItem> meshOrderItemList = new ArrayList<>();
        for (OrderItem orderItem : items) {
            MeshOrderItem meshOrderItem = new MeshOrderItem();
            BeanUtils.copyProperties(orderItem, meshOrderItem);
            meshOrderItemList.add(meshOrderItem);
        }
        //下单生成取餐码
        SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
        sideBoardCellDetail.setId(0);
        sideBoardCellDetail.setOrderStatus(0);
        sideBoardCellDetail.setOrderId(binguoOrder.getOrderno());
        sideBoardCellDetail.setBranchId(form.getBranchId());
        sideBoardCellDetail.setShopId(form.getShopId());
        String code = getMealCode(binguoOrder.getOrderno());

        sideBoardCellDetail.setMealCode(code);
        sideBoardVO1.setMealCode(code);
        System.out.println("sideBoardVO1:"+sideBoardVO1);
        int i = insertSideBoardCellDetail(sideBoardCellDetail);
        System.err.println("插入返回结果:"+i);
        try{
            wxCustomerService.saveOrder(binguoOrder, items, meshOrder, meshOrderItemList);
            return sideBoardVO1;
        }catch(Exception e){
            return null;
        }

    }


    public SideBoardVO qrCodePhoneMeals(PhoneMealsForm form,String sn){
        logger.info(form.toString());
        logger.info(sn);
        AiyouweiGetCellVO aiyouweiGetCellVO =
                selectAllNotUseCell(form.getBranchId(),form.getShopId());
        if(null == aiyouweiGetCellVO){
            return null;
        }
        if(null == form.getDeviceId()){
            form.setDeviceId(form.getCashierDeskId());
        }
        Long totalPrice = 0l;
        Integer meshOrderSerialInt = 0;
        String orderNo = orderNoBuilder.createPlatformOrderNo();
        SideBoardVO sideBoardVO =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());
        SideBoardVO sideBoardVO1 = sideBoardMapper.selectByShopIdAndBranchId(form.getBranchId(),form.getShopId(),form.getCashierDeskId());
        logger.info(sideBoardVO1.toString());
        totalPrice += sideBoardVO.getPrice();
        if(form.getIsWarm() == true){
            totalPrice += sideBoardVO.getWarm();
        }
        BinguoOrder binguoOrder = BinguoOrder.builder().id(0)
                .orderno(orderNo)
                .serial(meshOrderSerialInt.toString())
                .serialnumber(orderNo)
                .created(new Date())
                .customerphone(form.getPhone())
                .totalfee(totalPrice)
                .realfee(totalPrice).openid(null==form.getOpenId()?"":form.getOpenId())
                .cashierdeskid(form.getCashierDeskId())
                .ordertype(10).customerid(null)
                .paystatus(new Byte("1"))
                .refundfee(0L).note(form.getOrderDetailUrl())
                .shopid(form.getShopId())
                .totalquantity(1)
                .branchid(form.getBranchId()).transactionid(sn)
                .isMeals(1)
                .isWarm(form.getIsWarm() == true ? 1:0)
                .customername(form.getName())
                .build();
        List<OrderItem> items = new ArrayList<>();
        items.add(OrderItem.builder()
                .orderno(orderNo)
                .productid(-5)
                .productname("自定义菜品")
                .price(0L)
                .realprice(0L)
                .quantity(1)
                .created(new Date())
                .updated(new Date()).build());
        MeshOrder meshOrder = new MeshOrder();

        BeanUtils.copyProperties(binguoOrder, meshOrder);
        meshOrder.setReadStatus(0);


        List<MeshOrderItem> meshOrderItemList = new ArrayList<>();
        for (OrderItem orderItem : items) {
            MeshOrderItem meshOrderItem = new MeshOrderItem();
            BeanUtils.copyProperties(orderItem, meshOrderItem);
            meshOrderItemList.add(meshOrderItem);
        }
        //下单生成取餐码
        SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
        sideBoardCellDetail.setId(0);
        sideBoardCellDetail.setOrderStatus(0);
        sideBoardCellDetail.setOrderId(binguoOrder.getOrderno());
        sideBoardCellDetail.setBranchId(form.getBranchId());
        sideBoardCellDetail.setShopId(form.getShopId());
        sideBoardCellDetail.setSideBoardId(form.getDeviceId());
        String code = getMealCode(binguoOrder.getOrderno());
        logger.info("取餐码:"+code);

        sideBoardCellDetail.setMealCode(code);
        sideBoardVO1.setMealCode(code);
        System.out.println("sideBoardVO1:"+sideBoardVO1);
        int i = insertSideBoardCellDetail(sideBoardCellDetail);
        System.err.println("插入返回结果:"+i);
        try{
            wxCustomerService.saveOrder(binguoOrder, items, meshOrder, meshOrderItemList);
            return sideBoardVO1;
        }catch(Exception e){
            return null;
        }

    }


    public  SideBoardVO saveHdOrder(PhoneMealsForm form,Product product){
        AiyouweiGetCellVO aiyouweiGetCellVO =
                selectAllNotUseCell(form.getBranchId(),form.getShopId());
        if(null == aiyouweiGetCellVO){
            return null;
        }
        Long totalPrice = 0l;
        Integer meshOrderSerialInt = 0;
        String orderNo = orderNoBuilder.createPlatformOrderNo();
        SideBoardVO sideBoardVO1 = sideBoardMapper.selectByShopIdAndBranchId(form.getBranchId(),form.getShopId(),form.getCashierDeskId());
        BinguoOrder binguoOrder = BinguoOrder.builder()
                .orderno(orderNo)
                .serial(meshOrderSerialInt.toString())
                .serialnumber(orderNo)
                .created(new Date())
                .totalfee(product.getPrice())
                .realfee(product.getPrice())
                .cashierdeskid(form.getCashierDeskId())
                .ordertype(11)
                .paystatus(new Byte("0"))
                .refundfee(0L)
                .shopid(form.getShopId())
                .totalquantity(1)
                .branchid(form.getBranchId())
                .isMeals(1)
                .isWarm(form.getIsWarm() ==true ? 1:0)
                .build();
        List<OrderItem> items = new ArrayList<>();
        items.add(OrderItem.builder()
                .orderno(orderNo)
                .productid(product.getId())
                .productname(product.getName())
                .price(product.getPrice())
                .realprice(product.getPrice())
                .quantity(1)
                .created(new Date())
                .updated(new Date()).build());
        MeshOrder meshOrder = new MeshOrder();

        BeanUtils.copyProperties(binguoOrder, meshOrder);
        meshOrder.setReadStatus(0);


        List<MeshOrderItem> meshOrderItemList = new ArrayList<>();
        for (OrderItem orderItem : items) {
            MeshOrderItem meshOrderItem = new MeshOrderItem();
            BeanUtils.copyProperties(orderItem, meshOrderItem);
            meshOrderItemList.add(meshOrderItem);
        }
        //下单生成取餐码
        SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
        sideBoardCellDetail.setId(0);
        sideBoardCellDetail.setOrderStatus(0);
        sideBoardCellDetail.setOrderId(binguoOrder.getOrderno());
        sideBoardCellDetail.setBranchId(form.getBranchId());
        sideBoardCellDetail.setShopId(form.getShopId());
        String code = getMealCode(binguoOrder.getOrderno());

        sideBoardCellDetail.setMealCode(code);
        sideBoardVO1.setMealCode(code);
        System.out.println("sideBoardVO1:"+sideBoardVO1);
        int i = insertSideBoardCellDetail(sideBoardCellDetail);
        System.err.println("插入返回结果:"+i);
        try{
            wxCustomerService.saveOrder(binguoOrder, items, meshOrder, meshOrderItemList);
            return sideBoardVO1;
        }catch(Exception e){
            return null;
        }
    }

    public Map<String,String> prepareQrCodePhoneMeals(PhoneMealsForm form,String sn){
        Long totalPrice = 0l;
        Integer meshOrderSerialInt = 0;
        String orderNo = orderNoBuilder.createPlatformOrderNo();
        SideBoardVO sideBoardVO =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());
        totalPrice += sideBoardVO.getPrice();
        if(form.getIsWarm() == true){
            totalPrice += sideBoardVO.getWarm();
        }
        BinguoOrder binguoOrder = BinguoOrder.builder().id(0)
                .orderno(orderNo)
                .serial(meshOrderSerialInt.toString())
                .serialnumber(orderNo)
                .created(new Date())
                .customerphone(form.getPhone())
                .totalfee(totalPrice)
                .realfee(totalPrice).openid(null==form.getOpenId()?"":form.getOpenId())
                .cashierdeskid(null)
                .ordertype(10).customerid(null)
                .paystatus(new Byte("1"))
                .refundfee(0L).note(form.getOrderDetailUrl())
                .shopid(form.getShopId())
                .totalquantity(1)
                .branchid(form.getBranchId()).transactionid(sn)
                .isMeals(1)
                .isWarm(0)
                .customername(form.getName())
                .build();
        List<OrderItem> items = new ArrayList<>();
        items.add(OrderItem.builder()
                .orderno(orderNo)
                .productid(-5)
                .productname("自定义菜品")
                .price(0L)
                .realprice(0L)
                .quantity(1)
                .created(new Date())
                .updated(new Date()).build());
        MeshOrder meshOrder = new MeshOrder();

        BeanUtils.copyProperties(binguoOrder, meshOrder);
        meshOrder.setReadStatus(0);


        List<MeshOrderItem> meshOrderItemList = new ArrayList<>();
        for (OrderItem orderItem : items) {
            MeshOrderItem meshOrderItem = new MeshOrderItem();
            BeanUtils.copyProperties(orderItem, meshOrderItem);
            meshOrderItemList.add(meshOrderItem);
        }
        //下单生成取餐码
        SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
        sideBoardCellDetail.setId(0);
        sideBoardCellDetail.setOrderStatus(0);
        sideBoardCellDetail.setOrderId(binguoOrder.getOrderno());
        sideBoardCellDetail.setBranchId(form.getBranchId());
        sideBoardCellDetail.setShopId(form.getShopId());
        String code = getMealCodeByShopAndBranch(form.getShopId(),form.getBranchId());
        sideBoardCellDetail.setMealCode(code);
        sideBoardCellDetail.setPhone(form.getPhone());
        int i = insertSideBoardCellDetail(sideBoardCellDetail);
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        map.put("orderNo",orderNo);
        try{
            wxCustomerService.saveOrder(binguoOrder, items, meshOrder, meshOrderItemList);
            return map;
        }catch(Exception e){
            return null;
        }

    }


    /**
     * 生成四位不重复取餐码2
     * @return
     */
    public String getMealCodeByShopAndBranch(Integer shopId,Integer branchId){
        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
        criteria.andBranchIdEqualTo(branchId);
        criteria.andShopIdEqualTo(shopId);
        criteria.andMealCodeIsNotNull();
        List<SideBoardCellDetail> sideBoardCells = sideBoardCellDetailMapper.selectByExample(example);
        return getNewArray(sideBoardCells);

    }

}